from datetime import datetime, timedelta

import uvicorn
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from jose import jwt
from sqlalchemy.orm import Session
from starlette.staticfiles import StaticFiles

import models
from auth import pwd_context, SECRET_KEY
from db import get_db, engine
from dictionary import dictionary_get, dictionary_post,dictionary_put
from harp import harp_get, harp_post
from user import user_get, user_post


models.Base.metadata.create_all(bind=engine)
app = FastAPI()
app.mount(path="/storage", app=StaticFiles(directory="./storage"), name="storage")

@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}

@app.post("/token")
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    user = db.query(models.User).filter(models.User.phone == form_data.username).first()
    if not user:
        raise HTTPException(status_code=401, detail="用户不存在")
    if not pwd_context.verify(form_data.password, user.password):
        raise HTTPException(status_code=401, detail="密码错误")
    expiration = datetime.utcnow() + timedelta(hours=24)
    token = jwt.encode({"user_id": user.id, "exp": expiration}, SECRET_KEY, algorithm="HS256")
    return {"access_token": token, "toke_type": "bearer", "code": 200}


app.include_router(user_get.router)
app.include_router(user_post.router)
app.include_router(dictionary_get.router)
app.include_router(dictionary_post.router)
app.include_router(harp_get.router)
app.include_router(harp_post.router)



if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8001)
